﻿using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ElectronicCommerce.Framework.Web.Utility
{
    public enum StringStartedSymbol
    {
        SingleQuotes,
        DoubleQuotes,

    }
    public static class JavascriptUtility
    {
        private static Regex s_dr = new Regex("[\x00-\x1f\x22\x5c\x7f-\x9f]", RegexOptions.Multiline);
        private static Regex s_sr = new Regex("[\x00-\x1f\x27\x5c\x7f-\x9f]", RegexOptions.Multiline);

        /// <summary>
        /// Encode javascript string
        /// </summary>
        /// <param name="value"></param>
        /// <param name="symbol"></param>
        /// <returns>encoded javascript string</returns>
        public static string StringEncoding(string value, StringStartedSymbol symbol)
        {
            Regex r = null;
            switch (symbol)
            {
                case StringStartedSymbol.SingleQuotes:
                    r = s_sr;
                    break;
                case StringStartedSymbol.DoubleQuotes:
                    r = s_dr;
                    break;
            }

            if (!string.IsNullOrEmpty(value))
            {
                char[] charArray = value.ToCharArray();
                List<string> output = new List<string>();
                foreach (char c in charArray)
                {
                    int n = (int)c;
                    switch (n)
                    {
                        case 0x22:
                            // only escape if this charater is being used as the delimiter
                            output.Add((symbol == StringStartedSymbol.DoubleQuotes) ? "\\\"" : @"""");
                            break;
                        case 0x27:
                            // only escape if this charater is being used as the delimiter
                            output.Add((symbol == StringStartedSymbol.SingleQuotes) ? @"\'" : @"'");
                            break;
                        default:
                            if (n > 0x1f && n < 0x80 && n != 0x5c)
                            {
                                output.Add(c.ToString());
                            }
                            else
                            {
                                output.Add("\\u" + string.Format("{0:x4}", n));
                            }
                            break;
                    }
                }

                return string.Join("", output.ToArray());
            }
            return value;
        }
    }
}
